package com.nm.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * Created by zhangyaosheng on 2018/5/11.
 */
@WebFilter(filterName = "fontLoginFilter", urlPatterns = {"/*"})
public class FontLoginFilter implements Filter {
    final static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(FontLoginFilter.class);
    public FilterConfig config;

    public void init(FilterConfig filterConfig) {
        config = filterConfig;
        logger.info("初始化前台登录验证过滤器");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper((HttpServletResponse) response);

        String uri = httpRequest.getRequestURI();
        Boolean aBoolean = excludePath(uri);
        if (aBoolean) {
            //包含静态资源路径，直接放行
            filterChain.doFilter(servletRequest, response);
            return;
        }

        //要过滤的前台请求路径
        String[] filterUrlList = new String[]{"apply", "sign", "checking", "successReset", "successRegister", "myApply", "items"};
        String[] adminUrlList = new String[]{"manage"};
        if (this.isContains(uri, filterUrlList)) {
            //获取session，如果为null,直接跳转登录页面
            HttpSession session = httpRequest.getSession();
            Object user = session.getAttribute("user");

            if (user == null) {
                //尚未登录，跳转登录页面
                logger.error("前台登录拦截器：尚未登录");
                wrapper.sendRedirect("./");
                return;
            } else {
                filterChain.doFilter(servletRequest, response);
            }
        } else if (this.isContains(uri, adminUrlList)) {//因为前台登录和后台管理登录路径不同，所以要做区分；
            //获取session，如果为null,直接跳转登录页面
            HttpSession session = httpRequest.getSession();
            Object user = session.getAttribute("adminUser");

            if (user == null) {
                //尚未登录，跳转后台管理登录页面
                logger.error("前台登录拦截器：尚未登录");
                wrapper.sendRedirect("adminLogin");
                return;
            } else {
                filterChain.doFilter(servletRequest, response);
            }
        } else {
            filterChain.doFilter(servletRequest, response);
            return;
        }
    }

    public static boolean isContains(String container, String[] regx) {
        boolean result = false;

        for (int i = 0; i < regx.length; i++) {
            if (container.indexOf(regx[i]) != -1) {
                return true;
            }
        }
        return result;
    }

    public void destroy() {
        this.config = null;
    }

    //判断当前路径是否包含静态资源路径
    public Boolean excludePath(String url) {
        //判断路径是否包含静态资源路径
        if (url.endsWith(".css")
                || url.endsWith(".js")
                || url.endsWith(".jpg")
                || url.endsWith(".png")
                || url.contains("/frame/")
                ) {
            return true;
        } else {
            return false;
        }
    }
}
